package com.suncp.scheduler;

import com.suncp.job.PrintWordsJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Notice: 调度器
 *
 * @author scp
 * @version 1.0
 * @date 2021/3/10
 * @since 1.0
 */
public class MyScheduler {
    public static void main(String[] args) throws SchedulerException, InterruptedException {

        // 1.创建调度器
        StdSchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Scheduler scheduler = schedulerFactory.getScheduler();

        // 2.创建JobDetail实例，并与PrintWordsJob类绑定(job执行内容)
        JobDetail jobDetail = JobBuilder.newJob(PrintWordsJob.class).withIdentity("job1", "group1")
                .usingJobData("jobDetail1", "这个Job用来测试的.") // 测试jobDataMap存值，job中JobExecutionContext可以获取存储的信息 【可有可无】
                .build();

        // 3.构建Trigger实例，每隔1s执行一次
        Date startDate = new Date();
        startDate.setTime(startDate.getTime() + 5000);
        Date endDate = new Date();
        endDate.setTime(startDate.getTime() + 5000);

        SimpleTrigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "triggerGroup1")
                .startNow() // 立即生效
                .startAt(startDate)
                .endAt(endDate)
                .usingJobData("trigger1", "这是jobDetail的trigger.")  // 测试jobDataMap存值，job中JobExecutionContext可以获取存储的信息 【可有可无】
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        // 每隔1s执行一次
                        .withIntervalInSeconds(1)
                        .repeatForever()).build(); // 一直执行

        // 4.执行 每隔1s执行一次，一分钟后结束
        scheduler.scheduleJob(jobDetail, trigger);
        System.out.println("==========scheduler start !==============");
        scheduler.start();

        // 睡眠
        TimeUnit.SECONDS.sleep(10);
        scheduler.shutdown();
        System.out.println("==========scheduler shutdown !==============");
    }
}
